package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.Util;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String blogId=req.getParameter("blogId");
        User user= Util.checkLoginStatus(req);
        if (user==null){
            resp.setContentType("text/html; charset=utf-8");
            String html="<h3>当前用户未登录</h3>";
            resp.getWriter().write(html);
            return;
        }
        if (blogId==null){
            String jsonString=objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        }else {
            BlogDao blogDao=new BlogDao();
            Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
            if (blog==null){
                String html="博客不存在";
                resp.setContentType("text/html; charset=utf-8");
                resp.getWriter().write(html);
                return;
            }
            UserDao userDao=new UserDao();
            User author=userDao.selectById(blog.getUserId());
            author.setIsYourBlog(user.getUserId()==author.getUserId()?1:0);
            String jsonString=objectMapper.writeValueAsString(author);

            resp.getWriter().write(jsonString);
        }
    }


}
